package com.fxu.framework.biz.holder;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.fxu.framework.biz.rest.impl.ApiProxyRestImpl;
import com.fxu.framework.biz.util.LoginUtil;
import com.fxu.framework.biz.util.TokenUtil;
import com.fxu.framework.core.base.Constant;
import com.fxu.framework.core.base.ResultCode;
import com.fxu.framework.core.exception.MsgException;
import com.fxu.framework.core.holder.SpringHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 文件存储读取基础类
 * @author fangxu
 * @version 1.3.4
 */
@Slf4j
@Component("fxuTokenHolder")
public final class TokenHolder {
	private static TokenHolder holder = null;
	public static TokenHolder getHolder() {
		if (holder == null) {
			holder = SpringHolder.getBean("fxuTokenHolder");
		}
		return holder;
	}

	/**
	 * 获取登录信息[可能返回null]
	 * @param request 请求
	 * @param clazz 返回对象类
	 * @param <T> 返回对象范型
	 * @return 返回登录信息
	 */
	public <T> T getTokenDtoMayNull(HttpServletRequest request, Class<T> clazz) {
		if (request == null || clazz == null) {
			return null;
		}
		String token = TokenUtil.getToken(request);
		if (StrUtil.isEmpty(token)) {
			return null;
		}
		Map<String, Object> userInfo = LoginUtil.getInfo(token);
		if (userInfo == null) {
			return null;
		}
		return BeanUtil.toBean(userInfo, clazz);
	}

	/**
	 * 获取登录信息,null跑出异常
	 * @param request 请求
	 * @param clazz 返回对象类
	 * @param <T> 返回对象范型
	 * @return 返回登录信息
	 */
	public <T> T getTokenDtoNotNull(HttpServletRequest request, Class<T> clazz) {
		T dto = getTokenDtoMayNull(request, clazz);
		if (dto == null) {
			throw new MsgException(ResultCode.NEED_LOGIN);
		}
		return dto;
	}

}